<?php
//自定义页面
namespace app\common\controller;

use app\common\middleware\Auth;
use app\common\service\Sql as SqlService;
use think\facade\Config;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;

class Shop
{
    protected $middleware = [Auth::class => []];

    /*
    列表模板
    */
    public function Index()
    {
        return ViewTpl('/common/shop/lists');
    }

    public function Userinfo()
    {
        return ViewTpl('/common/shop/userinfo');
    }

    public function Detail()
    {
        return ViewTpl('/common/shop/detail');
    }

    public function Confirm()
    {
        return ViewTpl('/common/shop/confirm');
    }

    public function Addon()
    {
        $rows = [];
        $dir = App()->getRootPath() . "addon/";
        if (is_dir($dir)) {
            if ($handle = opendir($dir)) {
                while (($file = readdir($handle)) !== false) {
                    if ($file != "." && $file != "..") {
                        $copyPath = $dir . DIRECTORY_SEPARATOR . $file;
                        $config = $this->InstallConfig($copyPath, 'info');
                        if (!empty($config)) {
                            $config['addon_num'] = $file;
                            $rows[] = $config;
                        }
                    }
                }
                closedir($handle);
            }
        }
        foreach ($rows as $k => $v) {
            $rows[$k]['tags'] = !empty($v['tags']) ? explode(',', $v['tags']) : [];
            if (input("keyword")) {
                $name = !empty($v['name']) ? $v['name'] : '';
                $t = explode(input("keyword"), $name);
                if (count($t) <= 1) {
                    unset($rows[$k]);
                }
            }
        }
        $rows = array_values($rows);
        $data['rows'] = $rows;
        $data['total'] = count($rows);
        return BackCode($data);
    }


    //安装应用
    public function Install()
    {
        $addon = input('addon');
        if (empty($addon)) {
            return BackCode([], 203, '应用编码不能为空');
        }
        $copyPath = App()->getRootPath() . "addon/" . $addon . "/";
        if (!file_exists($copyPath)) {
            return BackCode([], 203, '没有此应用');
        }
        $this->InstallSql($copyPath . 'database/install.sql');
        $this->InstallPath($copyPath . '/path', App()->getRootPath(), 1);//复制文件到对应目录
        $info = $this->InstallConfig($copyPath, 'info');
        $info['install'] = 2;
        $this->FileInfo($info, $copyPath . 'config/info.php');
        return BackCode([], 200, '安装成功');
    }


    public function InstallSql($install)
    {
        if (file_exists($install)) {
            $SqlService = new SqlService();
            $arr = $SqlService->getSqlFromFile($install);
            $preFix = Config::get('database.connections.mysql.prefix');
            $sql = $SqlService->ReplacePreFix($arr, $preFix);//替换前缀
            foreach ($sql as $k => $v) {
                Db::query($v);
            }
        }
    }

    public function InstallConfig($Path = '', $type = 'menu')
    {
        $Path = $Path . '/config/' . $type . '.php';
        $config = [];
        if (file_exists($Path)) {
            $config = include $Path;
        }
        return $config;
    }

    public function InstallPath($source, $destination, $child, $fileb = '')
    {

        if (!file_exists($destination)) {
            if (!mkdir(rtrim($destination, '/'), 0777, true)) {
                return false;
            }
            @chmod($destination, 0777);
        }
        if (!is_dir($source)) {
            return false;
        }
        if (!is_dir($destination)) {
            mkdir($destination, 0777, true);
        }
        $handle = dir($source);
        while ($entry = $handle->read()) {
            if (($entry != ".") && ($entry != "..")) {
                if (is_dir($source . "/" . $entry)) {
                    if ($child)
                        $this->InstallPath($source . "/" . $entry, $destination . "/" . $entry, $child, $fileb);
                } else {
                    if ($fileb) {
                        if (strpos($fileb, $entry) !== false) {
                            copy($source . "/" . $entry, $destination . "/" . $entry);
                        }
                    } else {
                        copy($source . "/" . $entry, $destination . "/" . $entry);
                    }
                }
            }
        }
        return true;
    }


    public function Download()
    {

        $token = Request::header('utoken');
        $order_id = input('order_id');
        if (empty($order_id)) {
            return BackCode([], 203, '订单ID不能为空');
        }
        if (empty($token)) {
            return BackCode([], 203, '用户信息不能为空');
        }
        $filePath = App()->getRootPath() . 'addon/' . date('YmdHis') . '.zip';
        $api = GetConfig('system','shop_url').'api/addon/download/';
        $params = ['order_id' => $order_id];
        $headers = array(
            'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
            'token:' . $token
        );
        $response = GetHttp($api, $params, 'POST', $headers);
        if (str_starts_with($response, '{')) {
            $back = json_decode($response, true);
            return BackCode([], $back['code'], $back['msg']);
        }
        $file = file_put_contents($filePath, $response, true);
        if (empty($file)) {
            return BackCode([], 203, '下载失败');
        }
        $unzip = $this->unzip_file($filePath, App()->getRootPath() . "addon");
        if (empty($unzip)) {
            return BackCode([], 203, '解压失败');
        }
        unlink($filePath);//删除压缩包
        return BackCode([], 200, $unzip . '安装成功');
    }


    function unzip_file($file, $destination)
    {
        $num = false;
        $zip = new \ZipArchive;
        if ($zip->open($file) === true) {
            $result = $zip->extractTo($destination);
            $zip->close();
            if ($result) {
                $num = true;
            }
        }
        return $num;
    }


    //卸载应用
    public function Uninstall()
    {
        $addon = input('addon');
        if (empty($addon)) {
            return BackCode([], 203, '应用编码不能为空');
        }
        $copyPath = App()->getRootPath() . "addon/" . $addon . "/";
        if (!file_exists($copyPath)) {
            return BackCode([], 203, '没有此应用');
        }
        $list1 = $this->getFiles($copyPath . 'path/', 1);//获取所有文件
        $list2 = array_reverse($this->getFiles($copyPath . 'path/', 2));//获取所有文件
        foreach ($list1 as $k => $v) {
            $path = str_replace('addon/' . $addon . '/path//', '', $v);
            if (file_exists($path)) {
                unlink($path);//删除文件
            }
        }
        foreach ($list2 as $k => $v) {
            $path = str_replace('addon/' . $addon . '/path//', '', $v);
            if (is_dir($path)) {
                if (count(scandir($path)) == 2) {
                    rmdir($path);//删除空文件夹
                }
            }
        }
        $this->InstallSql($copyPath . 'database/uninstall.sql');//卸载数据库
        $info = $this->InstallConfig($copyPath, 'info');
        $info['install'] = 1;
        $this->FileInfo($info, $copyPath . 'config/info.php');
        return BackCode([], 200, '卸载成功');
    }

    public function LocalInfo($addon_num = '')
    {
        $addon = $addon_num ?: input('addon');
        $copyPath = App()->getRootPath() . "addon/" . $addon . "/";
        $config = $this->InstallConfig($copyPath, 'info');
        if (input("addon")) {
            return BackCode($config);
        }
        return $config;
    }


    public function LocalFile()
    {
        $file = Request::file("file");
        $path = App()->getRootPath() . 'public/storage/' . Filesystem::disk('public')->putFile('addon', $file);
        $unzip = $this->unzip_file($path, App()->getRootPath() . "addon");
        if ($unzip) {
            return BackCode([], 200, '上传成功');
        }
        return BackCode([], 203, '上传失败');
    }

    /*生成配置文件*/
    public function FileInfo($info = [], $path = '')
    {
        $str = '<?php' . PHP_EOL;
        $str .= 'return [' . PHP_EOL;
        foreach ($info as $field => $value) {
            $str .= "    '" . $field . "' =>'" . $value . "'," . PHP_EOL;
        }
        $str .= "];";
        getCreatetxt($path, $str);
    }

    public function getFiles($dir, $type)
    {
        $files = [];
        if (is_dir($dir)) {
            $handle = opendir($dir);
            while (($file = readdir($handle)) !== false) {
                if ($file != '.' && $file != '..') {
                    $path = $dir . '/' . $file;
                    if (is_dir($path)) {
                        if ($type == 2) {
                            $files[] = $path;
                        }
                        $files = array_merge($files, $this->getFiles($path, $type));
                    } else {
                        if ($type == 1) {
                            $files[] = $path;
                        }

                    }
                }
            }
            closedir($handle);
        }
        return $files;
    }


}
